//
//  DDZhuDaVC.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/10/6.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDZhuDaVC.h"
#import "UIImageView+WebCache.h"
#import "MWPhoto.h"
#import "DDMediaVC.h"
#import "DDMediaIV.h"

#import "DDTagDB.h"
#import "DDNetWorkAPIClient.h"

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
@interface DDZhuDaVC ()<UITextViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *datas;
@property(nonatomic,strong)NSArray * answerImageArray;
@property(nonatomic,strong)NSMutableArray *photos;

@property (nonatomic,strong)UITextView *fillTextView;
@property (retain, nonatomic) AVAudioPlayer *avPlay;

@property (nonatomic,strong)NSString *storeText;
@end

@implementation DDZhuDaVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
}

-(void)commit{
    [self showHUD:@"正在提交..."];
    
    
    
    //答案集合上传
    NSString *explanationJson=@"";
    NSMutableArray *explanations = [NSMutableArray array];

    
    NSDictionary *pngDict = @{@"type":@"TEXT",@"text":_fillTextView.text,@"url":@""};
    [explanations addObject:pngDict];
    
    
    
    for (int i = 0; i < _datas.count ; i++) {
        NSString *ext = [_datas[i] pathExtension];
        if ([ext isEqualToString:@"jpg"]) {
            //                    NSDictionary *pngDict = @{@"type":@"IMAGE",@"url":answers[i]};
            //                    [explanations addObject:pngDict];
            //保存泡泡标签
            NSArray *tags =   [DDTagDB searchWithWhere:[NSString stringWithFormat:@"qid='%@' ",_reply.answerId] orderBy:nil offset:0 count:0];
            NSMutableArray *filterArray = [NSMutableArray array];
            for (int i = 0; i < tags.count; i++) {
                DDTagDB *tag = tags[i];
                if (![filterArray containsObject:tag.tagIndex]) {
                    [filterArray addObject:tag.tagIndex];
                }
                
            }
            NSArray *sortArray = [NSArray arrayWithArray:filterArray];
            [sortArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                
                NSString *o1 = (NSString *)obj1;
                NSString *o2 = (NSString *)obj2;
                if ([o1 integerValue] > [o2 integerValue]) {
                    return NSOrderedAscending;
                }
                if ([o1 integerValue] < [o2 integerValue]) {
                    return NSOrderedDescending;
                }
                return NSOrderedSame;
            }];
            
            if (sortArray.count > i) {
                NSArray *tagss =   [DDTagDB searchWithWhere:[NSString stringWithFormat:@"qid='%@' AND tagIndex='%@'",_reply.answerId,sortArray[i]] orderBy:nil offset:0 count:0];
                
                NSMutableArray *tagLabels = [NSMutableArray array];
                
                for (DDTagDB *tagdb in tagss) {
                    if ([tagdb.type isEqualToString:@"IMAGE"]||[tagdb.type isEqualToString:@"AUDIO"]) {
                        NSDictionary *dict = @{@"type":[tagdb.type isEqualToString:@"AUDIO"]?@"VOICE":tagdb.type,@"x":[NSNumber numberWithInteger:[tagdb.x integerValue]],@"y":[NSNumber numberWithInteger:[tagdb.y integerValue]],@"url":tagdb.result};
                        [tagLabels addObject:dict];
                    }else if ([tagdb.type isEqualToString:@"TEXT"]){
                        NSDictionary *dict = @{@"type":tagdb.type,@"x":[NSNumber numberWithInteger:[tagdb.x integerValue]],@"y":[NSNumber numberWithInteger:[tagdb.y integerValue]],@"text":tagdb.result};
                        [tagLabels addObject:dict];
                    }
                }
                NSDictionary *pngDict = @{@"type":@"IMAGE",@"url":_datas[i],@"labels":tagLabels};
                [explanations addObject:pngDict];
                
            }else{
                NSDictionary *pngDict = @{@"type":@"IMAGE",@"url":_datas[i]};
                [explanations addObject:pngDict];
            }
            
            
        }
        if ([ext isEqualToString:@"caf"]) {
            NSDictionary *cafDict = @{@"type":@"VOICE",@"url":_datas[i]};
            [explanations addObject:cafDict];
        }
        
    }
    
    NSError *error;
    NSData * JSONData = [NSJSONSerialization dataWithJSONObject:explanations
                                                        options:kNilOptions
                                                          error:&error];
    explanationJson = [[NSString alloc]initWithData:JSONData encoding:NSUTF8StringEncoding];

    
    NSDictionary * tempDic = nil;
//    if ([_reply.parent integerValue] != 0) {
//        tempDic = @{
//                    @"answerId" : self.info_element.id,
//                    @"content" : param_content,
//                    @"parent" : @"",
//                    };
//    }else{
        tempDic = @{
                    @"answerId" : _reply.answerId,
                    @"content" : explanationJson,
                    @"parent" : _reply.id,
                    };
//    }
    __weak DDZhuDaVC *weakSelf = self;
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    [network mainQuestionReply:tempDic completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
//        if ([object[@"message"] isEqualToString:@"成功"]) {
//            [self.navigationController popViewControllerAnimated:YES];
//        }
        [weakSelf hideHUD];
        [weakSelf delayHUD:@"提交成功!"];
         [[NSNotificationCenter defaultCenter] postNotificationName:@"clearTagView" object:nil];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
}
//-(BOOL)assembleDic{
//    BOOL isSuccess = NO;
//    /*
//     [
//     {
//     "id": 17,
//     "type": "TEXT",
//     "title": null,
//     "text": "这是测试的题目",
//     "url": null,
//     "description": null,
//     "labels": null
//     }
//     ]
//     */
//    if (param_dataArray.count > 0 || self.textView_reply.text.length > 0) {
//        isSuccess = YES;
//    }
//    if (self.fillTextView.text.length > 0) {
//        [param_dataArray addObject:@{@"type": @"TEXT" , @"text" : self.fillTextView.text}];
//    }
//    
//    
//    
//    param_content = [param_dataArray JSONString];
//    
//    return isSuccess;
//}
#pragma mark - textviewDelegate
- (void)textViewDidChangeSelection:(UITextView *)textView{
    NSLog(@"textViewDidChangeSelection:");
    _storeText =textView.text;
}
- (void)createUI
{
    __weak DDZhuDaVC *weakSelf = self;
    self.view.backgroundColor = RGB(245, 245, 245);
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    //自定义TAB BAR UI
    [self addNavigatorTitle:NSLocalizedString(@"追答", nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];
    [self AddLeftBtnAction:nil normal:@"top_返回" selected:@"top_返回" action:^{
        //[self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [self AddRightBtnAction:@"提交" normal:nil selected:nil action:^{
        [weakSelf commit];
    }];
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
    
    
    _datas = [NSMutableArray array];
    
    //增加一个控制器，用来做多媒体那块
    DDMediaVC *vc = [[DDMediaVC alloc] initWithNibName:@"DDMediaVC" bundle:nil];//[DDMediaView loadFromNib];
    [self addChildViewController:vc];
    UIView * mediaView = vc.view;
    mediaView.frame = CGRectMake(0, self.view.frame.size.height - 132, self.view.frame.size.width, 132);
    mediaView.backgroundColor = [UIColor whiteColor];
    vc.mediaForPhoto = ^(UIImage *image,NSString *url)
    {
//        DDQuestionView *qview = self.view.scrollView.subviews[_currentPage];
//        [qview reloadDataForAnswers:image url:url];
        [_datas addObject:url];
        [self.tableView reloadData];
    };
    vc.mediaForAudio = ^(NSString *path,NSString *time,NSString *url)
    {
//        DDQuestionView *qview = self.view.scrollView.subviews[_currentPage];
//        [qview reloadDataForAnswers:path time:time url:url];
        [_datas addObject:url];
        [self.tableView reloadData];
    };
    [self.view addSubview:mediaView];
    
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(popTagView:) name:@"popTagView" object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(clearPopTagView) name:@"clearTagView" object:nil];
}

-(void)clearPopTagView
{
    [[self.view viewWithTag:10001] removeFromSuperview];
}
- (void)popTagView:(NSNotification *)note
{
    
    UIView *view = [self.view viewWithTag:10001];
    if (view) {
        [self clearPopTagView];
        return;
    }
    
    DDTagVC * _tagVC = [[DDTagVC alloc] initWithNibName:@"DDTagVC" bundle:nil];
    [self addChildViewController:_tagVC];
    NSDictionary *dict = note.object;
    _tagVC.x = [dict objectForKey:@"x"];
    _tagVC.y = [dict objectForKey:@"y"];
    _tagVC.index = [dict objectForKey:@"index"];
    _tagVC.qid = [dict objectForKey:@"qid"];
    _tagVC.page = [dict objectForKey:@"page"];
    CGRect rect = _tagVC.view.frame;
    _tagVC.view.frame = CGRectMake((self.view.frame.size.width-rect.size.width)/2, self.view.frame.size.height, rect.size.width, rect.size.height);
    _tagVC.view.tag = 10001;
    [self.view addSubview:_tagVC.view];
    _tagVC.view.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _tagVC.view.frame = CGRectMake((self.view.frame.size.width-rect.size.width)/2, self.view.frame.size.height/2, rect.size.width, rect.size.height);
    }];
    
//    int selectPage = (int)_tagVC.page.integerValue - 1;
    __weak DDZhuDaVC *weakSelf = self;
    _tagVC.result = ^(NSString *result,id object,NSString *type)
    {
        NSLog(@"%@",result);
        [weakSelf.tableView reloadData];
//        NSArray *views = weakSelf.view.scrollView.subviews;
//        if (views.count > 0) {
//           // DDQuestionView *qview = views[selectPage];
//           // [qview.tableView reloadData];
//        }
    };
}

#pragma mark -UITableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (_reply.content && _reply.content.count > 0) {
            int height = 80;
            for (DDQuestionAnswerReplyContent *content in _reply.content) {
                if ([content.type isEqualToString:@"TEXT"]) {
                    height += [self autoLabelString:self.tableView string:content.text].height;
                }
                else if([content.type isEqualToString:@"IMAGE"])
                {
                    height += 300;
                }
            }
            return height;
        }
        return 0;
    }else if(indexPath.section == 1){
        int height = 110;
        if (_datas.count > 0) {//资源
            for (NSString *url in _datas) {
                 if (![[url lowercaseString] hasSuffix:@"caf"]) {
                     NSURL *nsurl = [NSURL URLWithString:url];
                     UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:nsurl]];
                     CGSize size = [self autoImage:image];
                    height += size.height;
                }else{
                    height += 63;
                }
                
            }
            return height;
        }
        return height;
    }
    return  0;
}


- (CGSize)autoLabelString:(UIView *)view string:(NSString *)s
    {
        UIFont *font = [UIFont fontWithName:@"Arial" size:17.0];
        
        NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
        paragraphStyle.alignment = NSTextAlignmentLeft;
        
        NSDictionary * attributes = @{NSFontAttributeName : font,
                                      NSParagraphStyleAttributeName : paragraphStyle};
        
        CGSize contentSize = [s boundingRectWithSize:CGSizeMake(self.view.frame.size.width, MAXFLOAT)
                                             options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                          attributes:attributes
                                             context:nil].size;
        return contentSize;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        //cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    if (indexPath.section == 0) {
        
        float start_X = 5;
        float start_Y = 5;
        
        UIImageView *header_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(start_X, start_Y, 50, 50)];
        //header_imageView.image = [UIImage imageNamed:@"user_header"];
        [header_imageView sd_setImageWithURL:[NSURL URLWithString:_reply.userAvatarUrl] placeholderImage:[UIImage imageNamed:@"首页列表头像-通用"]options:SDWebImageRefreshCached];
        header_imageView.layer.cornerRadius = 25.0;
        header_imageView.layer.masksToBounds = YES;
        [cell.contentView addSubview:header_imageView];
        
        UILabel *name_label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:header_imageView sp:10],header_imageView.frame.origin.y+5 , 200, 24)];
        name_label.text = _reply.userName;
        name_label.textColor = RGB(124,203,203);
        [cell.contentView addSubview:name_label];
        
        UILabel *time_label = [[UILabel alloc] initWithFrame:CGRectMake(name_label.frame.origin.x,[self yPostiong:name_label sp:5] , 200, 16)];
        time_label.text = [self convertTime:_reply.createTime];//@"1天前";
        time_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
        time_label.textColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:time_label];
        
        
        NSArray *contents = _reply.content;
        int height = [self yPostiong:header_imageView sp:10];
        for (DDQuestionAnswerReplyContent *content in contents) {
            if ([content.type isEqualToString:@"TEXT"]) {
                UILabel *content_label = [[UILabel alloc] initWithFrame:CGRectMake(header_imageView.frame.origin.x,height , tableView.frame.size.width -10, [self autoLabelString:self.tableView string:content.text].height)];
                content_label.numberOfLines = 0;
                content_label.font = [UIFont fontWithName:@"Arial" size:17];
                content_label.text = content.text;
                [cell.contentView addSubview:content_label];
                height+=[self autoLabelString:self.tableView string:content.text].height;
            }else if([content.type isEqualToString:@"IMAGE"])
            {
                _answerImageArray = @[content.url];
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, height , tableView.frame.size.width - 20, 300)];
                [imageView sd_setImageWithURL:[NSURL URLWithString:content.url] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]options:SDWebImageRefreshCached];
                [cell.contentView addSubview:imageView];
                //imageView.contentMode =  UIViewContentModeScaleAspectFill;
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = imageView.frame;
                [button addTarget:self action:@selector(handleAnswerSingleTapImage) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:button];
                
                height += 300;
            }
        }
        
        
    }else if(indexPath.section == 1){
        
        _fillTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, self.tableView.frame.size.width-10, 90)];
        _fillTextView.layer.borderWidth = 1.0;
        _fillTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _fillTextView.layer.cornerRadius = 10;
        _fillTextView.delegate = self;
        _fillTextView.text = _storeText;
        [cell.contentView addSubview:_fillTextView];
        
        
        
        if (_datas.count > 0) {//资源
            int tagCount = 100;
            int height = 105;
            for (NSString *urlString in _datas) {
                //if ([[url lowercaseString] hasPrefix:@"jpg"] || [[url lowercaseString] hasPrefix:@"png"]) {
                if (![[urlString lowercaseString] hasSuffix:@"caf"]) {
                    NSURL *url = [NSURL URLWithString:urlString];
                    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
                    
                    CGSize size = [self autoImage:image];
                    cell.userInteractionEnabled = YES;
                    cell.contentView.userInteractionEnabled = YES;
                   
                    DDMediaIV *answerImageView = [[DDMediaIV alloc] initWithFrame:CGRectMake(5,height,size.width, size.height)];
                    
                    answerImageView.qid = _reply.answerId;
                    //answerImageView.tagIndex =  [NSString stringWithFormat:@"%ld",(long)_answerIndex];
                    answerImageView.tagIndex =  [NSString stringWithFormat:@"%ld",(long)indexPath.section];
                    [answerImageView addMedias];
                    answerImageView.popMediaView = ^(CGPoint point)
                    {
                        //DDMediaVC *mediaVC = [[DDMediaVC alloc] initWithNibName:@"DDMediaVC" bundle:nil];
                        //mediaVC.view.frame = CGRectMake(point.x, point.y, 150, 150);
                        //[self addSubview:mediaVC.view];
                        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                        [dict setValue:[NSString stringWithFormat:@"%f",point.x] forKey:@"x"];
                        [dict setValue:[NSString stringWithFormat:@"%f",point.y] forKey:@"y"];
                        // [dict setValue:[NSString stringWithFormat:@"%ld",(long)_answerIndex ] forKey:@"index"];
                        [dict setValue:[NSString stringWithFormat:@"%ld",(long)indexPath.section ] forKey:@"index"];
                        
                        [dict setValue:[NSString stringWithFormat:@"%@",_reply.answerId] forKey:@"qid"];
                        [dict setValue:[NSString stringWithFormat:@"%ld",(long)1] forKey:@"page"];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"popTagView" object:dict];
                        
                    };
                    answerImageView.userInteractionEnabled = YES;
                    answerImageView.image = image;
                    [cell.contentView addSubview:answerImageView];
                    
                     height+= size.height;
                    
                    //}
                    
                }else{
                    UIButton *answerButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    answerButton.frame = CGRectMake(5,height,108, 48);
                    [answerButton setImage:[UIImage imageNamed:@"play_audio"] forState:UIControlStateNormal];
                    [answerButton addTarget:self action:@selector(playAudio:) forControlEvents:UIControlEventTouchUpInside];
                    //answerButton.tag = indexPath.section;
                    [cell.contentView addSubview:answerButton];
                    answerButton.tag = tagCount;
//                    UILabel * timeLable = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:answerButton sp:5], height, 100, 32)];
//                    NSString *temp = urlString;
//                    NSArray *arr = [temp componentsSeparatedByString:@"|"];
//                    if (arr.count > 0) {
//                        NSString *s = arr[1];
//                        timeLable.text = [NSString stringWithFormat:@"%d\"",s.intValue];
//                    }
                   
//                    [cell.contentView addSubview:timeLable];
                    
                    height+=63;
                }
                 tagCount ++;
            }
            
        }
       
        
    }
    
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"clearTagView" object:nil];
}

- (NSString *)convertTime:(NSString *)time
{
    if (!time || [@"" isEqualToString:time]) {
        return @"";
    }
    
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //用[NSDate date]可以获取系统当前时间
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:time.longLongValue/1000];
    NSString *dateStr = [dateFormatter stringFromDate:d];
    return dateStr;
    
    return @"";
}

- (CGSize)autoImage:(UIImage *)image
{
    float w = image.size.width/2;
    float h = image.size.height/2;
    if (w > self.tableView.frame.size.width - 10) {
        //tw/th = w/h = c;
        float c = (self.tableView.frame.size.width - 10)/w;
        float tw = self.tableView.frame.size.width - 10;
        float th = h*c;
        
        return CGSizeMake(tw, th);
    }else{
        return CGSizeMake(w, h);
    }
    
}
-(void)playAudio:(UIButton *)sender
{
    NSInteger section = sender.tag - 100;
    NSString *temp = _datas[section];
    NSArray *arr = [temp componentsSeparatedByString:@"|"];
    if (arr.count > 0) {
        if (self.avPlay.playing) {
            [self.avPlay stop];
            return;
        }
        NSURL *url = [[NSURL alloc] initFileURLWithPath:arr[0]];
        AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
        self.avPlay = player;
        [self.avPlay play];
    }
}

-(void)handleAnswerSingleTapImage
{
    NSLog(@"123123");
    _photos = [NSMutableArray array];
    
    for (int i = 0; i < _answerImageArray.count ; i++) {
        NSString *url = _answerImageArray[i];
        NSRange range = [url rangeOfString:@"http://"];//判断字符串是否包含
        if (range.length >0)//包含
        {
            MWPhoto   *photo = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
            //photo.caption = _friendInfo.username;
            [_photos addObject:photo];
        }else{
            continue;
        }
    }
    
    [[NSNotificationCenter defaultCenter]  postNotificationName:@"DisPlayImage" object:_photos];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
